package top.codestudy.storageandroid10;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private Button mBtnGoShareStorage;
    private Button mBtnGoSharedPreferences;

    private EditText mEtInternalStorage;
    private Button mBtnInternalStorage;
    private EditText mEtExternalStorage;
    private Button mBtnExternalStorage;
    private EditText mEtExternalStorageDir;
    private Button mBtnExternalStorageDir;
    private EditText mEtInternalStorageDir;
    private Button mBtnInternalStorageDir;

    private EditText mEtFileName;
    private Button mBtnIsFileInInternal;
    private Button mBtnIsFileInExternal;
    private Button mBtnDelFileInInternal;
    private Button mBtnDelFileInExternal;

    private Button mBtnShowFilePath;
    private Button mBtnShowAllFileInInternal;
    private Button mBtnShowAllFileInExternal;
    private TextView mTvShowLog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        XXPermissions.with(this)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
    }

    private void initView() {
        //控件类的代码组织，也应该跟随layout布局的块来组织
        mBtnGoShareStorage = findViewById(R.id.btn_go_share_storage);
        mBtnGoShareStorage.setOnClickListener(this);
        mBtnGoSharedPreferences = findViewById(R.id.btn_go_shared_preferences);
        mBtnGoSharedPreferences.setOnClickListener(this);
        mEtInternalStorage = findViewById(R.id.et_internal_storage);
        mBtnInternalStorage = findViewById(R.id.btn_internal_storage);
        mEtExternalStorage = findViewById(R.id.et_external_storage);
        mBtnExternalStorage = findViewById(R.id.btn_external_storage);
        mEtExternalStorageDir = findViewById(R.id.et_external_storage_dir);
        mBtnExternalStorageDir = findViewById(R.id.btn_external_storage_dir);
        mEtInternalStorageDir = findViewById(R.id.et_internal_storage_dir);
        mBtnInternalStorageDir = findViewById(R.id.btn_internal_storage_dir);
        mBtnInternalStorage.setOnClickListener(this);
        mBtnExternalStorage.setOnClickListener(this);
        mBtnExternalStorageDir.setOnClickListener(this);
        mBtnInternalStorageDir.setOnClickListener(this);

        mEtFileName = findViewById(R.id.et_file_name);
        mBtnIsFileInInternal = findViewById(R.id.btn_is_file_in_internal);
        mBtnIsFileInExternal = findViewById(R.id.btn_is_file_in_external);
        mBtnDelFileInInternal = findViewById(R.id.btn_del_file_in_internal);
        mBtnDelFileInExternal = findViewById(R.id.btn_del_file_in_external);

        mBtnShowFilePath = findViewById(R.id.btn_show_file_path);
        mBtnShowAllFileInInternal = findViewById(R.id.btn_show_all_file_in_internal);
        mBtnShowAllFileInExternal = findViewById(R.id.btn_show_all_file_in_external);
        mTvShowLog = findViewById(R.id.tv_show_log);
        mBtnIsFileInInternal.setOnClickListener(this);
        mBtnIsFileInExternal.setOnClickListener(this);
        mBtnDelFileInInternal.setOnClickListener(this);
        mBtnDelFileInExternal.setOnClickListener(this);

        mBtnShowFilePath.setOnClickListener(this);
        mBtnShowAllFileInInternal.setOnClickListener(this);
        mBtnShowAllFileInExternal.setOnClickListener(this);
    }

    //获取内部存储 私有文件的文件名
    public String getEtInternalStorageStr() {
        return mEtInternalStorage.getText().toString();
    }

    //获取外部存储 私有文件的文件名
    public String getEtExternalStorage() {
        return mEtExternalStorage.getText().toString();
    }

    //获取外部存储 私有文件的目录名
    public String getEtExternalStorageDir() {
        return mEtExternalStorageDir.getText().toString();
    }

    //获取内部存储 私有文件的目录名
    public String getEtInternalStorageDir() {
        return mEtInternalStorageDir.getText().toString();
    }

    //获取文件的文件名
    public String getEtFileName() {
        return mEtFileName.getText().toString();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        String filename_is_exist = getEtFileName();
        switch (v.getId()) {
            case R.id.btn_go_share_storage:
                SharedStorageActivity.goSharedStorageActivity(MainActivity.this);
                break;
            case R.id.btn_go_shared_preferences:
                SharedPreferencesActivity.goSharedPreferencesActivity(MainActivity.this);
                break;
            case R.id.btn_internal_storage:
                //任务：将文件存储在内部存储中
                String filename = getEtInternalStorageStr();
                if (filename != null && !"".equals(filename)) {
                    File file = new File(getFilesDir(), filename);
                    if (!file.exists()) {
                        try {
                            boolean newFile = file.createNewFile();
                            if (newFile) {
                                showShort("InternalStorage : 文件创建成功！");
                            } else {
                                showShort("InternalStorage : 文件创建失败！");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            showShort("InternalStorage : IOException ==> 文件创建失败！");
                        }
                    } else {
                        showShort("InternalStorage : file is exists ！！！");
                    }
                } else {
                    showShort("InternalStorage : file name is null");
                }
                break;
            case R.id.btn_external_storage:
                //任务：将文件存储在外部存储中
                String filename_External = getEtExternalStorage();
                if (filename_External != null && !"".equals(filename_External)) {
                    File appSpecificExternalDir = new File(getExternalFilesDir(null), filename_External);
                    if (!appSpecificExternalDir.exists()) {
                        try {
                            boolean newFile = appSpecificExternalDir.createNewFile();
                            if (newFile) {
                                showShort("ExternalStorage : 文件创建成功！");
                            } else {
                                showShort("ExternalStorage : 文件创建失败！");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            showShort("ExternalStorage : IOException ==> 文件创建失败！");
                        }
                    } else {
                        showShort("ExternalStorage : file is exists ！！！");
                    }
                } else {
                    showShort("ExternalStorage : file name is null");
                }
                break;
            case R.id.btn_external_storage_dir:
                //任务：存储目录到外部存储中
                String dirname_External = getEtExternalStorageDir();
                if (dirname_External != null && !"".equals(dirname_External)) {
                    File appSpecificExternalDir = new File(getExternalFilesDir(null), dirname_External);
                    if (!appSpecificExternalDir.exists()) {
                        boolean newFile = appSpecificExternalDir.mkdirs();
                        if (newFile) {
                            showShort("ExternalStorage : 目录创建成功！");
                        } else {
                            showShort("ExternalStorage : 目录创建失败！");
                        }
                    } else {
                        showShort("ExternalStorage : 目录 exists ！！！");
                    }
                } else {
                    showShort("ExternalStorage : 目录名 is null");
                }
                break;
            case R.id.btn_internal_storage_dir:
                createDir();
                break;
            case R.id.btn_is_file_in_internal:
                //文件是否存在 在内部存储目录中
                if (filename_is_exist != null && !"".equals(filename_is_exist)) {
                    File file = new File(getFilesDir(), filename_is_exist);
                    if (file.exists()) {
                        showShort("文件： " + filename_is_exist + " 存在内部存储目录中！");
                    } else {
                        showShort("文件： " + filename_is_exist + " 不存在内部存储目录中！");
                    }
                } else {
                    showShort("InternalStorage : file name is null");
                }
                break;
            case R.id.btn_is_file_in_external:
                //文件是否存在 在外部存储目录中
                if (filename_is_exist != null && !"".equals(filename_is_exist)) {
                    File appSpecificExternalDir = new File(getExternalFilesDir(null), filename_is_exist);
                    if (appSpecificExternalDir.exists()) {
                        showShort("文件： " + filename_is_exist + " 存在外部存储目录中！");
                    } else {
                        showShort("文件： " + filename_is_exist + " 不存在外部存储目录中！");
                    }
                } else {
                    showShort("ExternalStorage : file name is null");
                }
                break;
            case R.id.btn_del_file_in_internal:
                //在内部存储中删除此文件
                if (filename_is_exist == null || "".equals(filename_is_exist)){
                    showShort("filename_is_exist is null");
                    return;
                }
                File file2Del = new File(getFilesDir(), filename_is_exist);
                if (file2Del.exists()){
                    boolean delete = file2Del.delete();
                    if (delete){
                        showShort("删除成功！");
                    }else {
                        showShort("删除失败！");
                    }
                }
                break;
            case R.id.btn_del_file_in_external:
                //在外部存储中删除此文件

                break;
            case R.id.btn_show_file_path:
                //任务：显示内部存储以及外部存储各自的根路径
                File internalRootPath = getFilesDir();
                File externalRootPath = getExternalFilesDir(null);
                assert externalRootPath != null;
                mTvShowLog.setText("internalRootPath => \n" + internalRootPath.getAbsolutePath()
                        + ";\nexternalRootPath => \n" + externalRootPath.getAbsolutePath());
                break;
            case R.id.btn_show_all_file_in_internal:
                String[] fileList = fileList();
                String str = "";
                for (String file : fileList) {
                    str += file + "\n";
                }
                mTvShowLog.setText(str);
                break;
            case R.id.btn_show_all_file_in_external:
                //外部存储比较特别，不做处理
                break;
        }
    }

    public void showShort(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        Log.d(TAG, "showShort: " + msg);
    }

    //创建目录在内部存储中
    public void createDir() {
        String dirname_internal = getEtInternalStorageDir();
        if (dirname_internal != null && !"".equals(dirname_internal)) {
            File appSpecificExternalDir = new File(getFilesDir(), dirname_internal);
            if (!appSpecificExternalDir.exists()) {
                boolean newFile = appSpecificExternalDir.mkdirs();
                if (newFile) {
                    showShort("InternalStorage : 目录创建成功！");
                } else {
                    showShort("InternalStorage : 目录创建失败！");
                }
            } else {
                showShort("InternalStorage : 目录 exists ！！！");
            }
        } else {
            showShort("InternalStorage : 目录名 is null");
        }
    }
}